package com.xzz.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xzz.domain.PayOrder;
import com.xzz.dto.Order2PayOrderParamDto;
import com.xzz.service.IPayOrderService;
import io.netty.util.CharsetUtil;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "service-pay-consumer",
        topic = "topic-order",
        selectorExpression="tag-order",
        messageModel = MessageModel.CLUSTERING
    )
public class PayOrderConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt message) {
        String msg = new String(message.getBody(), CharsetUtil.UTF_8);
        Order2PayOrderParamDto orderDto = JSON.parseObject(msg, Order2PayOrderParamDto.class);

        EntityWrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderDto.getOrderNo());
        PayOrder payOrder = payOrderService.selectOne(wrapper);

        //如果查到了，证明已经支付了，防重（幂等性），这是消费者的报错方式
        if (payOrder!=null){
            return;
        }

        payOrderService.savePayOrder(orderDto);
    }
}